/**
 * WebSocket客户端工具类
 */
export class WebSocketClient {
  constructor() {
    this.ws = null
    this.sessionId = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.isConnecting = false
    this.messageHandlers = new Map()
  }

  /**
   * 连接WebSocket
   */
  async connect(sessionId) {
    if (this.isConnecting || (this.ws && this.ws.readyState === WebSocket.OPEN)) {
      return
    }

    this.sessionId = sessionId
    this.isConnecting = true

    try {
      const wsUrl = `ws://127.0.0.1:9999/ws?sessionId=${sessionId}`
      console.log('连接WebSocket:', wsUrl)

      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log('WebSocket连接成功')
        this.isConnecting = false
        this.reconnectAttempts = 0
        this.emit('connected')
      }

      this.ws.onmessage = (event) => {
        this.handleMessage(event)
      }

      this.ws.onclose = (event) => {
        console.log('WebSocket连接关闭:', event.code, event.reason)
        this.isConnecting = false
        this.emit('disconnected', event)

        // 自动重连
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          this.scheduleReconnect()
        }
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.isConnecting = false
        this.emit('error', error)
      }

    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.isConnecting = false
      this.emit('error', error)
    }
  }

  /**
   * 发送文本消息
   */
  sendText(text) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(text)
      console.log('发送文本消息:', text)
    } else {
      console.warn('WebSocket未连接，无法发送消息')
    }
  }

  /**
   * 发送音频数据
   */
  sendAudio(audioData) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(audioData)
      console.log('发送音频数据，大小:', audioData.byteLength)
    } else {
      console.warn('WebSocket未连接，无法发送音频')
    }
  }

  /**
   * 处理接收到的消息
   */
  handleMessage(event) {
    try {
      // 尝试解析JSON消息
      const message = JSON.parse(event.data)
      console.log('收到JSON消息:', message)

      if (message.type === 'text') {
        this.emit('textMessage', message.message)
      } else if (message.type === 'audio') {
        this.emit('audioMessage', message.data)
      } else if (message.type === 'system') {
        this.emit('systemMessage', message.message)
      } else if (message.type === 'error') {
        this.emit('errorMessage', message.message)
      } else if (message.type === "OpenApp") {
        this.emit('openAppMessage', message.message)
      } else if (message.type === "FileSystem") {
        this.emit('fileSystemMessage', message.message)
      } else if (message.type === "AppOperation") {
        this.emit('appOperationMessage', message.message)
      } else if (message.type === "SupportOperationApp") {
        this.emit('supportOperationAppMessage', message.message)
      } else if (message.type === "tips") {
        this.emit('tipsMessage', message.message)
      } else {
        // 默认处理为文本消息  
        this.emit('textMessage', message.message || event.data)
      }
    } catch (error) {
      // 如果不是JSON，可能是二进制音频数据
      if (event.data instanceof ArrayBuffer) {
        console.log('收到音频数据，大小:', event.data.byteLength)
        this.emit('audioData', event.data)
      } else if (event.data instanceof Blob) {
        console.log('收到Blob数据，大小:', event.data.size)
        // 将Blob转换为ArrayBuffer
        event.data.arrayBuffer().then(buffer => {
          this.emit('audioData', buffer)
        })
      } else {
        console.log('收到原始消息:', event.data)
        this.emit('rawMessage', event.data)
      }
    }
  }

  /**
   * 安排重连
   */
  scheduleReconnect() {
    this.reconnectAttempts++
    const delay = this.reconnectInterval * Math.pow(2, this.reconnectAttempts - 1)

    console.log(`WebSocket重连尝试 ${this.reconnectAttempts}/${this.maxReconnectAttempts}，${delay}ms后重连`)

    setTimeout(() => {
      if (this.sessionId) {
        this.connect(this.sessionId)
      }
    }, delay)
  }

  /**
   * 添加消息处理器
   */
  on(event, handler) {
    if (!this.messageHandlers.has(event)) {
      this.messageHandlers.set(event, [])
    }
    this.messageHandlers.get(event).push(handler)
  }

  /**
   * 移除消息处理器
   */
  off(event, handler) {
    if (this.messageHandlers.has(event)) {
      const handlers = this.messageHandlers.get(event)
      const index = handlers.indexOf(handler)
      if (index > -1) {
        handlers.splice(index, 1)
      }
    }
  }

  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.messageHandlers.has(event)) {
      this.messageHandlers.get(event).forEach(handler => {
        try {
          handler(data)
        } catch (error) {
          console.error('消息处理器错误:', error)
        }
      })
    }
  }

  /**
   * 关闭连接
   */
  close() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.isConnecting = false
    this.reconnectAttempts = 0
  }

  /**
   * 获取连接状态
   */
  getConnectionState() {
    if (!this.ws) return 'disconnected'

    switch (this.ws.readyState) {
      case WebSocket.CONNECTING:
        return 'connecting'
      case WebSocket.OPEN:
        return 'connected'
      case WebSocket.CLOSING:
        return 'closing'
      case WebSocket.CLOSED:
        return 'disconnected'
      default:
        return 'unknown'
    }
  }

  /**
   * 是否已连接
   */
  isConnected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN
  }
}
